import React, { Fragment } from "react";
import ChartA from "./ChartA";
import { ChartContainer } from "../left/ChartContainer";
import { validPosition, drapEnd } from "../service/store";
import { Observable } from "rxjs/Observable";
import Chart from "./Chart";

interface IChart {
  name: string
  leftTop: [number, number]
  width: number
  height: number
}

class State {
  public charts: IChart[] = []
}
export default class Charts extends React.Component<{}, State> {

  public state = new State()

  public componentDidMount() {
    const validPositions$ = validPosition.buffer(drapEnd).map(positons => {
      const leftTop: [number, number] = [Math.min(...positons.map(positon => positon[0][0])), Math.min(...positons.map(positon => positon[0][1]))]
      const rightBottom = [Math.max(...positons.map(positon => positon[3][0])), Math.max(...positons.map(positon => positon[3][1]))]
      return { leftTop, width: rightBottom[0] - leftTop[0], height: rightBottom[1] - leftTop[1] }
    })
    Observable
      .combineLatest(drapEnd, validPositions$)
      .debounceTime(10)
      .subscribe(([name, option]) => {
        const charts = this.state.charts
        const foundIndex = charts.findIndex(c => c.name === name)
        const newChart = { name, ...option }
        if (foundIndex === -1) {
          newChart.name = `${newChart.name}-${Math.random().toString().substr(5, 10)}`
          charts.push(newChart)
        } else {
          charts[foundIndex] = newChart
        }
        this.setState({ charts })
      })
  }

  public render() {
    return (
      <Fragment>
        {this.state.charts.map(c => {
          const style = { left: c.leftTop[0], top: c.leftTop[1], height: c.height, width: c.width }
          const C = this.getCmp(c.name.split('-')[0])
          return <ChartContainer name={c.name} Cmp={C} key={name} style={style} />
        })}
      </Fragment>
    )
  }

  private getCmp(name: string): any {
    if (name === 'ChartA') {
      return ChartA
    } else if (name === "Chart") {
      return Chart
    }
  }

}